package com.project.shrio;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

import java.util.List;

public class ShiroTest {
//    public ShiroTest(){
//        //创建安全管理器
//        DefaultSecurityManager manager = new DefaultSecurityManager();
//        //设置权限认证数据来源，为类路径下的shiro.ini
//        manager.setRealm(new IniRealm("classpath:shiro.ini"));
//        //设置安全管理器
//        SecurityUtils.setSecurityManager(manager);
//        //得到主体
//        Subject subject = SecurityUtils.getSubject();
//        //产生用户名和密码的令牌
//        UsernamePasswordToken token = new UsernamePasswordToken("tom","123");
//        //登录认证
//        subject.login(token);
//        System.out.println("登录成功");
//    }
    public ShiroTest(){
        DefaultSecurityManager manager = new DefaultSecurityManager();
        manager.setRealm(new CustomRealm());
        SecurityUtils.setSecurityManager(manager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("tom","123");
        try {
            subject.login(token);
            System.out.println("登录成功");
            //查看当前用户是否具有指定权限“manager”
            System.out.println(subject.hasRole("manager"));
            //查看当前用户是否同时拥有“manager”和“order“两个权限
            System.out.println(subject.hasAllRoles(List.of("manager","order")));
            //查看当前用户是否具有指定的权限
            System.out.println(subject.isPermitted("user:create"));
            System.out.println(subject.isPermitted("user:delete"));
            //查看当前用户是否同时具有指定权限
            System.out.println(subject.isPermittedAll("user:create", "order:add"));
        }catch (UnknownAccountException e1){
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e2){
            System.out.println("密码错误");
        }

    }
    public static void main(String[] args) {
        new ShiroTest();
    }
}
